<?php
// +----------------------------------------------------------------------
// | Description: 用户
// +----------------------------------------------------------------------
// +----------------------------------------------------------------------

namespace app\admin\model;

use app\common\traits\ActionRecordTrait;
use app\crm\logic\BusinessLogic;
use app\crm\logic\ClientLogic;
use app\crm\logic\CustomerLogic;
use app\crm\logic\LeadsLogic;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\facade\Db;
use com\verify\HonrayVerify;
use think\facade\Cache;
use think\Request;

class User extends Common
{

    use ActionRecordTrait;

    /**
     * 为了数据库的整洁，同时又不影响Model和Controller的名称
     * 我们约定每个模块的数据表都加上相同的前缀，比如CRM模块用crm作为数据表前缀
     */
    protected $name = 'admin_user';
    protected $createTime = 'create_time';
    protected $updateTime = false;
    protected $autoWriteTimestamp = true;
    protected $insert = [
        'status' => 2,
    ];
    protected $statusArr = ['禁用','启用','未激活'];

    protected $dateFormat = 'Y-m-d';
    protected $type = [
        'create_time'    =>  'timestamp',
        'update_time'    =>  'timestamp',
    ];

    /**
     * 账号锁定key
     * @var string
     */
    protected $lockKey = 'login_lock_';

    /**
     * 账号锁定消息
     * @var string
     */
    protected $lockMsg = '';




    /**
     * 账号永久锁定消息提示
     */
    const LOCK_ACCOUNT_PERMANENT_MSG = '账号已经永久锁定,请联系管理员解锁';

    /**
     * 导入字段
     *
     * @var array
     * @author Ymob
     * @datetime 2019-10-25 15:35:25
     */
    public static $import_field_list = [
        [
            'field' => 'username',
            'name' => '手机号（登录名）',
            'form_type' => 'mobile',
            'is_null' => 1,
//			'is_unique' => 1 //guogaobo 导入此字段会进行验重查询调用修改用户方法
        ],
        [
            'field' => 'password',
            'name' => '密码',
            'form_type' => 'text',
            'is_null' => 1,
        ],
        [
            'field' => 'realname',
            'name' => '姓名',
            'form_type' => 'text',
            'is_null' => 1,
        ],
        [
            'field' => 'sex',
            'name' => '性别',
            'form_type' => 'select',
            'setting' => ['男', '女'],
            'is_null' => 0,
        ],
        [
            'field' => 'email',
            'name' => '邮箱',
            'form_type' => 'email',
            'is_null' => 0,
        ],
        [
            'field' => 'post',
            'name' => '岗位',
            'form_type' => 'text',
            'is_null' => 0,
        ]
    ];

    /**
     * 获取用户所属所有用户组
     * @param  array   $param  [description]
     */
    public function groups()
    {
        return $this->belongsToMany('group', 'admin_access', 'group_id', 'user_id');
    }


    public function structureList($structure_id,$str)
    {
        $str_ids = structureList($structure_id,$str);
        return $str_ids;
    }

    /**
     * [getDataList 列表]
     * @AuthorHTL
     * @param     [string]                   $map [查询条件]
     * @param     [number]                   $page     [当前页数]
     * @param     [number]                   $limit    [每页数量]
     * @param $request
     * @return array
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     * @author Mr.Li
     * @create 2021-06-05 11:48
     */
    public function getDataList($request)
    {
        $request = $this->fmtRequest( $request );
        $fieldarray = ['search','group_id','structure_id','status','type','page','limit','pageType'];
        $map = isset($request['map']) ? $request['map']: [];
        if (isset($map['search']) && $map['search']) {
            // $map['user.username|user.realname'] = ['like', '%'.$map['search'].'%'];
            $map[] = ['user.username|user.realname', 'like', '%'.$map['search'].'%'];
        }

        unset($map['search']);
        //角色员工
        $map['group_id'] = $map['group_id'] ?? '';
        if ($map['group_id']) {
            $group_user_ids =  Db::name('admin_access')->where(['group_id' => $map['group_id']])->column('user_id');
            if ($map['group_id'] == 1 && !$group_user_ids) {
                $group_user_ids = ['1'];
            }
           if($group_user_ids){
               $group_user_ids = implode(',',$group_user_ids);
           }
            $map[] = array('user.id','in',$group_user_ids);

        }
       // $exp = new \think\db\Expression('field(user.status,1,2,0)');
        // 默认除去超级管理员
        // $map['user.id'] = array('neq', 1);
        $map['structure_id'] = $map['structure_id'] ?? '';
        if($map['structure_id']){
            //获取部门下员工列表
            $str_ids = structureList($map['structure_id'],'');
            $new_str_ids = rtrim($str_ids,',');

            $map[] = ['user.structure_id','in',$new_str_ids]; //$map['structure_id'];
        }
        unset($map['structure_id']);

        $map['status'] = $map['status'] ?? 'all';
        $map['group_id'] = $map['group_id'] ?? '';
        if($map['status'] === ''){
            $map['status'] = 'all';
        }
        if ($map['status'] || $map['group_id']) {
            if ($map['status'] != 3) {
                $map[] = ($map['status'] !== 'all') ? ($map['status'] ? ['user.status','=',$map['status']] : ['user.status','>',0]) : ['user.status','>=',0];
            } else {
                $map[] = ['user.create_time','>', time() - 86400 * 7];
            }
        } else {
            $map[] = ['user.status','=',0];
        }
        unset($map['group_id']);
        unset($map['status']);

        $map[] = ['user.type','=',1];
        if(isset($map['type'])) $map['user.type'] == ($map['type'] == '0') ? 0 : 1;
        //过滤字段
        foreach($fieldarray as $value){
            unset($map[$value]);
        }

        //获取列表
        $dataCount = Db::name('AdminUser')
            ->alias('user')
            ->join('admin_structure structure', 'structure.id = user.structure_id', 'LEFT')
            // ->join('HrmUserDet hud','hud.user_id = user.id','LEFT')
            ->where($map)
            ->count();


        $list = Db::name('AdminUser')
            ->alias('user')
            ->join('admin_structure structure', 'structure.id = user.structure_id', 'LEFT')
            // ->join('HrmUserDet hud','hud.user_id = user.id','LEFT')
            ->limit(($request['page']-1)*$request['limit'], $request['limit'])
            ->where($map)
            ->field('user.id,user.username,user.img,user.thumb_img,user.realname,user.num,user.email,user.mobile,user.sex,user.structure_id,user.post,user.status,user.parent_id,user.type,user.create_time,structure.name as s_name')
           // ->order($exp)
            ->order('structure.level asc')
            ->order('user.id desc')
            ->select()->toArray();



        try{
            foreach ($list as $k=>$v) {

                //直属上级
                $list[$k]['status_name'] = $v['status']=='1' ? '激活' : ($v['status']=='2' ? '未激活' : '禁用');

               if($v['parent_id']){
                   $parentInfo = $this->getUserById($v['parent_id']);
                   $list[$k]['parent_name'] = $v['parent_id'] ? $parentInfo['realname'] : '';

               }else{
                   $list[$k]['parent_name'] =  '';
               }





                //角色
                $groupsArr = $this->find($v['id'])->groups;
                $groups = [];
                $groupids = [];

                foreach ($groupsArr as $key=>$val) {
                    $groups[] = $val['title'];
                    $groupids[] = $val['id'];
                }


                $list[$k]['groups'] = $groups ? implode(',',$groups) : '';


                $list[$k]['groupids'] = $groupids ? implode(',',$groupids) : '';
                $list[$k]['img'] = $v['img'] ? getFullPath($v['img']) : '';
                $list[$k]['thumb_img'] = $v['thumb_img'] ? getFullPath($v['thumb_img']) : '';
                $list[$k]['create_time'] = $v['create_time'] ? date('Y-m-d H:i:s', $v['create_time']) : '';
                $list[$k]['s_name'] = !empty($v['s_name']) ? $v['s_name'] : '';
                $list[$k]['structure_id'] = !empty($v['structure_id']) ? $v['structure_id'] : '';

            }
        }catch (\Exception $e){

        }

        $data = [];
        $data['list'] = $list;
        $data['dataCount'] = $dataCount;

        return $data;
    }

    /*
    *根据字符串展示参与人 use by work
    */
    public function getDataByStr($idstr)
    {
        $idArr = stringToArray($idstr);
        if (!$idArr) {
            return [];
        }
        $list = $this->field('id,username,realname,thumb_img')->where(['id' => ['in',$idArr]])->select();
        foreach($list as $key=>$value){
            $list[$key]['thumb_img'] = $value['thumb_img']?getFullPath($value['thumb_img']):'';
        }
        return $list;
    }




    /**
     * [getDataByMobile 根据手机号获取详情]
     * @param     string                   $mobile []
     * @return
     */
    public function getDataByMobile($mobile = '')
    {
        $data= Db::name('AdminUser')->where('username',$mobile)->field('id,salt,username,status,password')->find();
        if (!$data) {
            $this->error = '该手机号尚未注册';
            return false;
        }
        return $data;
    }

    /**
     * [forgetPassword ]
     * @param
     * @return
     */
    public function forgetPassword($updData)
    {
        $id = $updData['id'];
        /*
        $captcha = new HonrayVerify(config('captcha'));
        if (!$captcha->check($updData['verify_code'])) {
            $this->error = '图片验证码错误';
            return false;
        }
        unset($updData['verify_code']);
        unset($updData['id']);
        */
        Db::name('AdminUser')->where('id',$id)->update($updData);
        return true;
    }


    /**
     * [getDataById 根据主键获取详情]
     * @param string $id
     * @return array|false|\think\Model|null
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     * @author Mr.Li
     * @create 2021-06-05 11:49
     */
    public function getDataById($id = '',$field = '')
    {
        if(!$field){
            $field = '*';
        }
        $data = Db::name('admin_user')->field($field)->find($id);
        if (!$data) {
            $this->error = '暂无此数据';
            return false;
        }
        unset($data['authkey']);

        if(isset($data['structure_id'])) {
            $structureDet = Db::name('admin_structure')->field('id,name')->where('id','=',$data['structure_id'])->find();
            $data['structure_name'] = $structureDet['name'] ?? '';
        } else {
            $data['structure_name'] = '暂无';
        }
        if(isset($data['parent_id'])) {
            $parentDet = Db::name('admin_user')->field('id,realname')->where('id = '.$data['parent_id'].'')->find();
            $data['parent_name'] = $parentDet['realname'] ?? '';
        } else {
            $data['parent_name'] = '暂无';
        }
        $data['thumb_img'] =  isset($data['thumb_img']) ? getFullPath($data['thumb_img']) : '';
        $data['img'] = isset($data['img']) ? getFullPath($data['img']) : '';
        //unset($data['password']);

        //角色
        $groupsArr = self::find($id)->groups;
        $groups = [];
        $groupids = [];

        foreach ($groupsArr as $key=>$val) {
            $groups[] = $val['title'];
            $groupids[] = $val['id'];
        }
        $data['groups'] = $groups ? implode(',',$groups) : '';
        $data['groupids'] = $groupids ? implode(',',$groupids) : '';
        $data['is_login_lock'] = $this->isUserLoginLock('pc',$id) ? 1 : 0;
        $data['groupids'] = $groupids ? implode(',',$groupids) : '';
        isset($data['create_time']) && $data['create_time'] ? $data['create_time'] = date('Y-m-d H:i:s',$data['create_time']) : '';
        return $data;
    }

    /**
     * 创建用户
     * @param array $param
     * @return bool
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     * @author Mr.Li
     * @create 2021-06-05 11:50
     */
    public function createData($param)
    {
        // 非导入数据
        if (request()->action() == 'import') {
            $temp = [];
            foreach (self::$import_field_list as $key => $val) {
                $temp[$val['field']] = $param[$val['field']];
            }
            $param = $temp;
            $param['structure_id'] = 0;
            if(Db::name('admin_user')->where('username',$param['username'])->find()){
                $this->error = '手机号已存在';
                return false;
            }
        } else {

            if (empty($param['group_id']) || !is_array($param['group_id'])) {
                $this->error = '请至少勾选一个用户组';
                return false;
            }
        }
        // 验证

        $validate = new \app\admin\validate\AdminUser();
        if (!$validate->check($param)) {
            $this->error = $validate->getError();
            return false;
        }
       // $syncModel = new \app\admin\model\Sync();
        $this->startTrans();
        try {
            $salt = substr(md5(time()),0,4);
            $param['salt'] = $salt;
            $password = (new Password())->getDefaultPwd();
            $param['password'] = user_md5($password, $salt, $param['username']);
            $param['type'] = 1;
            $param['mobile'] = $param['username'];
            $groupId = $param['group_id'];
            unset($param['group_id']);
            unset($param['groupids']);
            if(isset($param['kingdee_salesperson_code'])){
                $param['kingdee_salesperson_code'] = trim($param['kingdee_salesperson_code']);
                if( mb_strlen($param['kingdee_salesperson_code'],'utf8') > 50){
                    $this->error = '金蝶销售员编码最多50位';
                    return false;
                }
            }

            $param['create_time'] = time();
            $user_id = $this->insertGetId($param);
            //员工档案
            $data['user_id'] = $user_id;
            $data['mobile'] = $param['username'];
            $data['email'] = $param['email'] ?? '';
            $data['sex'] = $param['sex'] ? : '';
            $data['create_time'] = time();
            Db::name('AdminHrmUserDet')->insert($data);

            $userGroups = [];
            foreach ($groupId as $k => $v) {
                $userGroup['user_id'] = $user_id;
                $userGroup['group_id'] = $v;
                $userGroups[] = $userGroup;
            }
            if ($userGroups) {
                Db::name('admin_access')->insertAll($userGroups);
            }

            $this->commit();
            $param['user_id'] = $data['user_id'];
            \think\facade\Cache::set('is_first_login:'.$data['user_id'],1);
           // $resSync = $syncModel->syncData($param);
            return true;
        } catch(\Exception $e) {
            $this->rollback();
            $this->error = '添加失败';
            return false;
        }
    }

    //导入成为正式用户
    public function beusers($request)
    {
        if ($request['userlist']&&is_array($request['userlist'])) {
            $flag = true;
            foreach ($request['userlist'] as $value) {
                $userInfo = Db::name('AdminUser')->where('id = '.$value.'')->find();
                $userDet = Db::name('AdminHrmUserDet')->where('user_id = '.$value.'')->find();
                $temp['status'] = 1;
                $temp['type'] = 1;
                $temp['username'] = $userDet['mobile'];
                $salt = substr(md5(time()),0,4);
                $temp['salt'] = $salt;
                $password = $userDet['mobile'];
                $temp['password'] = user_md5($password, $salt, $temp['username']);
                $flag = $flag && Db::name('AdminUser')->where('id ='.$value)->update($temp);
            }
            if ($flag) {
                return true;
            } else {
                $this->error = '操作失败';
                return false;
            }
        } else {
            $this->error = '参数错误';
            return false;
        }
    }

    /**
     * 通过id修改用户
     * @param $param
     * @param $id
     * @return bool
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     * @author Mr.Li
     * @create 2021-06-05 11:50
     */
    public function updateDataById($param, $id)
    {
        $param['user_id'] = $param['user_id'] ?? 0;
        if ($param['user_id']) {
            //修改个人信息
            $data['email'] = $param['email'];
            $data['sex'] = $param['sex'];
            // $data['mobile'] = $param['username'];

            $where = [
                ['username','=',$param['username']],
                ['id','<>',$param['user_id']],

            ];
            if (Db::name('admin_user')->where($where)->find()) {
                $this->error = '手机号已存在';
                return false;
            }
            Db::name('AdminHrmUserDet')->where(['user_id' => $param['user_id']])->update($data);
            $data['realname'] = $param['realname'];
            $data['post'] = $param['post'];
            if(isset($param['kingdee_salesperson_code'])){
                $data['kingdee_salesperson_code'] = trim($param['kingdee_salesperson_code']);
                if( mb_strlen($param['kingdee_salesperson_code'],'utf8') > 50){
                    $this->error = '金蝶销售员编码最多50位';
                    return false;
                }
            }
            $flag = $this->where(['id' => $param['user_id']])->update($data);
            if ($flag==0 || $flag==1) {
                return true;
            } else {
                $this->error = '保存失败';
                return false;
            }
        } else {
            // 不能操作超级管理员
            // if ($id == 1) {
            // 	$this->error = '非法操作';
            // 	return false;
            // }
            $checkData = $this->find($id);
            if (!$checkData) {
                $this->error = '暂无此数据';
                return false;
            }
            if (request()->action() != 'import') {
                if (empty($param['group_id'])) {
                    $this->error = '请至少勾选一个用户组';
                    return false;
                }
            }
            $subUserId = getSubUserId(true, 0, $id);
            if ((int)$param['parent_id'] == (int)$id) {
                $this->error = '直属上级不能是自己';
                return false;
            }
            if ((int)$param['parent_id'] !== 1 && in_array($param['parent_id'],$subUserId)) {
                $this->error = '直属上级不能是自己或下属';
                return false;
            }
            $where = [
                ['username','=',$param['username']],
                ['id','<>',$id],

            ];
            if (Db::name('admin_user')->where($where)->find()) {
                $this->error = '手机号已存在';
                return false;
            }


            $this->startTrans();
            try {
                $accessModel = new Access();
                if ($param['group_id']) {
                    //角色员工关系处理
                    $accessModel->userGroup($id, $param['group_id'], 'update');
                }
                unset($param['group_id'],$param['user_id']);

                if(isset($param['kingdee_salesperson_code'])){
                    $param['kingdee_salesperson_code'] = trim($param['kingdee_salesperson_code']);
                    if( mb_strlen($param['kingdee_salesperson_code'],'utf8') > 50){
                        $this->error = '金蝶销售员编码最多50位';
                        return false;
                    }
                }
                $this->where('id','=',$id)->update($param);
                $this->commit();
                //Cache::rm('user_info' . $id);

                // $data['mobile'] = $param['username'];
                $data['email'] = $param['email'];
                $data['sex'] = $param['sex'];
                $data['update_time'] = time();
                $flagg = Db::name('AdminHrmUserDet')->where('user_id','=',$id)->update($data);
                return true;
            } catch(\Exception $e) {
                $this->rollback();
                $this->error = '编辑失败';
                return false;
            }
        }
    }

    /**
     * 用户登陆
     * @param $username
     * @param $password
     * @param int $type 1系统用户 2 店铺账户
     * @param string $verify_code
     * @return array|false
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     * @author ran
     * @date 2021-09-15 14:07
     * mailbox 466180170@qq.com
     */
    public function login($username, $password,int $type,string $verify_code = '')
    {
        if (!$password){
            $this->error = '请输入密码';
            return false;
        }
        //验证码
        if (config('captcha')['identifying_code']) {
            if (!$verify_code) {
                $this->error = '请输入验证码';
                return false;
            }
            $captcha = new HonrayVerify(config('captcha'));
            if (!$captcha->check($verify_code,1)) {
                $this->error = '验证码错误';
                return false;
            }
        }
        $map['username'] = $username;
        $map['is_status'] = 0;
        $map['type'] = $type;
        $userInfo = $this->where($map)->find();
        if (!$userInfo) {
            $this->error = '登陆账户不存在,请您确认好登陆身份进行登录哦';
            return false;
        }
        // 登录记录
        $login_record = new LoginRecord();
        $login_record->user_id = $userInfo['id'];

        // 三次出错，十五分钟禁止登录
        /*
        if (!$login_record->verify()) {
            $this->error = $login_record->error;
            return false;
        }
        */

        $request = request();
        $header = $request->header();
        $platform = $header['platform'] ?? '';
        if($this->isLock($platform,$userInfo['id'])) {
            $this->error = $this->lockMsg;
            return false;
        }

        $userInfo['thumb_img'] = $userInfo['thumb_img'] ? config('app.img_url').$userInfo['thumb_img'] : '';
        if (user_md5($password, $userInfo['salt'], $userInfo['username']) !== $userInfo['password']) {

            $login_record->createRecord(LoginRecord::TYPE_PWD_ERROR,$platform);
            $this->error = $this->lockOperate($platform,$userInfo['id']);
            return false;
        }

        //用户锁定记录清除
        $this->clearLock($platform,$userInfo['id']);

        if ($userInfo['status'] === 0) {
            $this->error = '帐号已被禁用';
            $login_record->createRecord(LoginRecord::TYPE_USER_BANNED,$platform);
            return false;
        }
        //如果是app没有首页权限禁止登录
        if($platform && in_array($platform,['android','ios'])){
            $menuList = get_user_permission_menu($userInfo['id'],'home_list_tag',1);
            if(empty($menuList) || array_sum(array_values($menuList)) == 0){
                $this->error = '暂无app访问权限';
                return false;
            }
        }

        //如果首次登陆		
        if(\think\facade\Cache::has('is_first_login:'.$userInfo['id'])){//还没有修改密码
            if($this->isLoginJump()){
                header('Content-Type:application/json; charset=utf-8');
                exit(json_encode(['code'=>302,'msg'=>'首次登录需要重新修改密码','data' => ['id' => $userInfo['id']]]));
            }
        }
        $login_record->createRecord(LoginRecord::TYPE_SUCCESS,$platform);

        // 获取菜单和权限		
        if($platform && in_array($platform,['pc'])){			
            $dataList = $this->getMenuAndRule($userInfo['id'],$userInfo['shop_id']);			
        }

        //登录有效时间
        $cacheConfig = config('cache');
        $loginExpire = !empty($cacheConfig['expire']) ? $cacheConfig['expire'] : 86400 * 30;

        //删除无用信息
        unset($userInfo['salt'],$userInfo['password']);
        // 保存缓存
        session_start();
        $info['userInfo'] = $userInfo;
        $info['session_id'] = session_id();
        $authKey = user_md5($userInfo['username'].$userInfo['password'].$info['session_id'], $userInfo['salt']);
        // $info['_AUTH_LIST_'] = $dataList['rulesList'];
        $info['auth_key'] = $authKey;
        try{//删除旧缓存
            if(!Cache::handler()){
                $this->error = '请使用redis作为缓存';
                return false;
            }
            if (Cache::has('auth:'.$userInfo['auth_key'])) {
                //多端登录无需删除auth
                if(!Db::name('admin_pwd_rule')->order('id','asc')->value('multi_terminal_login')){
                    //清空所有登录用户缓存
                    $authKeyList = Cache::handler()->smembers('authUser:'.$userInfo['id']);
                    if(!empty($authKeyList)){
                        foreach ($authKeyList as $authKeyValue){
                            Cache::delete('auth:'.$authKeyValue);
                        }
                        Cache::delete('authUser:'.$userInfo['id']);
                    }
                }
            }
            Cache::set('auth:'.$authKey, $info, $loginExpire);
            Cache::handler()->sadd('authUser:'.$userInfo['id'], $authKey);
        }catch (\Exception $e) {
            $this->error = '登录失败';
            return false;
        }
        unset($userInfo['auth_key']);

        $accessModel = new Access();

        $dataAuth =$accessModel->getCommonUserDataAuth($userInfo['id']);

        $shopIds = $dataAuth['market']??[];
        $is_md = true;
        if(!empty($shopIds)){
            $md_shop = DB::name('shop')->where('shop_type',2)->where('status',1)->column('shop_id');//门店
            $mz_shop = DB::name('shop')->where('shop_type',1)->where('status',1)->column('shop_id');//门诊
            $md_diff=array_diff($shopIds,$md_shop);
            if(!empty($md_diff)){
                $is_md = false;
            }
            $mz_diff=array_diff($shopIds,$mz_shop);
            if(!empty($mz_diff)){
                $is_md = true;
            }
        }
        $userInfo['is_md'] = $is_md;

        //获取部门信息
        $userInfo['structure_name'] = Db::name('AdminStructure')->where('id','=',$userInfo['structure_id'])->value('name');
        
        // 获取职位信息
        $userInfo['position_id'] = Db::name('shop_person')->where('phone',$userInfo['mobile'])->value('position_id');
        // 返回信息
        $data['auth_key']		    = $authKey;
        $data['session_id']		    = $info['session_id'];
        $data['userInfo']		    = $userInfo;
        $data['menusList']		    = $dataList['menusList'] ?? [];
        $data['loginExpire']	    = $loginExpire;
        //保存authKey信息
        $userData = [];
        $userData['auth_key'] = $authKey;
        $userData['auth_key_time'] = time()+$loginExpire;
        $userData['last_login_at'] = date('Y-m-d H:i:s',time());
        //把状态未激活至为启用
        if ($userInfo['status'] == 2) {
            $userData['status'] = 1;
        }
        if(\think\facade\Cache::has('is_first_login:'.$userInfo['id'])){//登录成功就删除修改密码标识
            \think\facade\Cache::delete('is_first_login:'.$userInfo['id']);
        }
        //登录成功
        if(isset($data['userInfo']['parent_id'])) {
            $parentDet = Db::name('admin_user')->field('id,realname')->where('id = '.$data['userInfo']['parent_id'].'')->find();
            $data['userInfo']['parent_name'] = $parentDet['realname'] ?? '暂无';
        } else {
            $data['userInfo']['parent_name'] = '暂无';
        }
        $this->where(['id' => $userInfo['id']])->update($userData);
        return $data;
    }

    /**
     * 修改密码
     * @param  array   $param  [description]
     */
    public function updatePaw($userInfo, $old_pwd, $new_pwd,$type = 0)
    {
        if($type){
            if (!$new_pwd) {
                $this->error = '请输入新密码';
                return false;
            }
            if (!$old_pwd) {
                $this->error = '请输入旧密码';
                return false;
            }
        }
        //登录有效时间
        $cacheConfig = config('cache');
        $loginExpire = $cacheConfig['expire'] ?? 86400 * 3;

        $oldUserInfo = $this->where('id', $userInfo['id'])->find();
        if(!$oldUserInfo){
            $this->error = '账户不存在';
            return false;
        }
        $passwordRuleObj = new Password();
        if($type){//设置新密码
            if (user_md5($old_pwd, $oldUserInfo['salt'], $userInfo['username']) != $oldUserInfo['password']) {
                $this->error = '原密码错误';
                return false;
            }
            $ruleMsg = $passwordRuleObj->checkPwd($userInfo['username'],$old_pwd,$new_pwd,$new_pwd);
            if($ruleMsg){
                $this->error = $ruleMsg;
                return false;
            }
        }else{//重置密码
            $new_pwd = $passwordRuleObj->getDefaultPwd();
        }


        if ($this->where('id', $userInfo['id'])->update(['password' =>  user_md5($new_pwd, $oldUserInfo['salt'], $userInfo['username'])])) {

            $userInfo = $this->where('id', $userInfo['id'])->find();
            // 重新设置缓存
            session_start();
            $cache['userInfo'] = $userInfo;
            $cache['auth_key'] = user_md5($userInfo['username'].$userInfo['password'].session_id(), $userInfo['salt']);
            cache('auth:'.$cache['auth_key'], null);
            cache('auth:'.$cache['auth_key'], $cache, $loginExpire);
            return $cache['auth_key'];//把auth_key传回给前端
        }
        $this->error = '修改成功';
        return true;
    }

    //根据IDs批量设置密码
    public function updatePwdById($param)
    {
        $syncModel = new \app\admin\model\Sync();
        $flag = true;
        foreach ($param['id'] as $value) {
            $password = '';
            $userInfo = Db::name('admin_user')->where(['id' => $value])->find();;
            $salt = substr(md5(time()),0,4);
            $temp['salt'] = $salt;
            $temp['password']= $password = user_md5($param['password'], $salt, $userInfo['username']);
            $flag = $flag && Db::name('AdminUser')->where('id ='.$value)->update($temp);

            $syncData = [];
            $syncData['user_id'] = $value;
            $syncData['salt'] = $salt;
            $syncData['password'] = $password;
            $resSync = $syncModel->syncData($syncData);
        }
        if ($flag) {
            return $flag;
        } else {
            $this->error ='修改失败，请稍后重试';
            return false;
        }
    }

    /**
     * 获取菜单和权限 protected
     *
     * @param $u_id
     * @return array
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getMenuAndRule($u_id,$shopId)
    {
        // $menusList = [];
        $ruleMap   = [];
        $ruleMap[] = ['status', '=', 1];
        $adminTypes = adminGroupTypes($u_id);		
        $ret = [];
        if (in_array(1,$adminTypes)) {			
            //$menuList = Db::name('admin_menu')->where($ruleMap)->order('sort asc')->select();
            $menuList = ['*'];
        } else {			
            $groups = $this->find($u_id)->groups;
            $ruleIds = [];
            $menuIds = [];
            foreach ($groups as $k => $v) {
                /*
                if (stringToArray($v['rules'])) {
                    $ruleIds = array_merge($ruleIds, stringToArray($v['rules']));
                }
                */
                if (stringToArray($v['menus'])) {
                    $menuIds = array_merge($menuIds, stringToArray($v['menus']));
                }
            }
			/* echo '<pre>';
			print_r($menuIds);exit; */
            //得到前台菜单列表
            $menuMap[] = ['status','=',1];
            $menuMap[] = array('id','in',$menuIds);
            $shopType =Db::name('shop')->where('shop_id',$shopId)->value('type')??1;
            //var_dump($shopType);			
            $menuList = Db::name('admin_menu')->where($menuMap)->order('sort asc')->select()->toArray();			
            //获取前台菜单tree
            $tree = new \com\Tree();
            $menuList = $tree->list_to_tree($menuList, 'id', 'pid', 'child', 0, true, array('pid'));
            /* if($shopType ==2){
                 foreach ($menuList as $key=>$value){
                     if($value['id']==12){
                        unset($menuList[$key]);
                     }
                 }
            } */
        }

        //得到权限菜单数据处理菜单成树状
        /*
         *
        $ruleIds = array_unique($ruleIds);
        if($ruleIds){
            $ruleIds = implode(',',$ruleIds);
        }
        $ruleMap[] = ['id', 'in', $ruleIds];
        $newRuleIds = [];
        // 重新设置ruleIds，除去部分已删除或禁用的权限。
        $rules = Db::name('admin_rule')->where($ruleMap)->select()->toArray();
        foreach ($rules as $k => $v) {
            $newRuleIds[] = $v['id'];
            $rules[$k]['name'] = strtolower($v['name']);
        }

        $rulesList = $tree->list_to_tree($rules, 'id', 'pid', 'child', 0, true, array('pid'));
        $authList = rulesListToArray($rulesList, $newRuleIds);
        $ret['authList'] = $this->resetAuthorityFiled($authList);

        */

        $ret['menusList'] = array_values($menuList);
        return $ret;
    }

    /**
     * todo 应前端要求修改部分权限字段，与java的权限字段保持一致。
     *
     * @param $authList
     * @return mixed
     */
    private function resetAuthorityFiled($authList)
    {
        # 客户
        if (isset($authList['crm']['customer']['deal_status'])) {
            $authList['crm']['customer']['dealStatus'] = $authList['crm']['customer']['deal_status'];
            unset($authList['crm']['customer']['deal_status']);
        }
        if (isset($authList['crm']['customer']['nearby'])) {
            $authList['crm']['customer']['nearbyCustomer'] = $authList['crm']['customer']['nearby'];
            unset($authList['crm']['customer']['nearby']);
        }
        # 跟进记录
        if(isset( $authList['crm']['activity'])){
            $authList['crm']['followRecord'] = $authList['crm']['activity'];
        }

        # 公海
        if (isset($authList['crm']['customer']['pool'])) {
            $authList['crm']['pool']['index'] = $authList['crm']['customer']['pool'] ? true : false;
        }
        if (isset($authList['crm']['customer']['distribute'])) {
            $authList['crm']['pool']['distribute'] = $authList['crm']['customer']['distribute'] ? true : false;
        }
        if (isset($authList['crm']['customer']['receive'])) {
            $authList['crm']['pool']['receive'] = $authList['crm']['customer']['receive'] ? true : false;
        }
        if (isset($authList['crm']['customer']['poolexcelexport'])) {
            $authList['crm']['pool']['excelexport'] = $authList['crm']['customer']['poolexcelexport'] ? true : false;
        }
        if (isset($authList['crm']['customer']['pooldelete'])) {
            $authList['crm']['pool']['delete'] = $authList['crm']['customer']['pooldelete'] ? true : false;
        }
        # 合同
        if (isset($authList['crm']['contract']['discard'])) {
            $authList['crm']['contract']['discard'] = false;
        }
        # 发票
        if (isset($authList['crm']['invoice']['setinvoice'])) {
            $authList['crm']['invoice']['updateInvoiceStatus'] = $authList['crm']['invoice']['setinvoice'];
        }
        # 发票抬头权限
        if (!empty($authList['crm']['invoice']['index'])) {
            $authList['crm']['invoiceTitle']['index'] = true;
        }
        unset($authList['work']['work']);
        unset($authList['work']['task']);
        unset($authList['work']['taskclass']);
        # 跟进记录
        if (!empty($authList['crm']['record']['index'])) {
            $authList['crm']['followRecord']['delete'] = true;
            $authList['crm']['followRecord']['read'] = true;
            $authList['crm']['followRecord']['save'] = true;
            $authList['crm']['followRecord']['update'] = true;
        }
        unset($authList['crm']['record']);
        # admin:system
        if (!empty($authList['admin']['system']['index'])) {
            $authList['admin']['system']['read'] = $authList['admin']['system']['index'];
            unset($authList['admin']['system']['index']);
        }
        if (!empty($authList['admin']['system']['save'])) {
            $authList['admin']['system']['update'] = $authList['admin']['system']['save'];
        }
        # admin:configSet
        if (!empty($authList['admin']['configset']['index'])) {
            $authList['admin']['configSet']['read'] = $authList['admin']['configset']['index'];
        }
        if (!empty($authList['admin']['configset']['update'])) {
            $authList['admin']['configSet']['update'] = $authList['admin']['configset']['update'];
        }
        unset($authList['admin']['configset']);
        # admin:users
        if (!empty($authList['admin']['users']['index'])) {
            $authList['admin']['users']['read'] = $authList['admin']['users']['index'];
            unset($authList['admin']['users']['index']);
        }
        if (!empty($authList['admin']['users']['enables'])) {
            $authList['admin']['users']['userEnables'] = $authList['admin']['users']['enables'];
            unset($authList['admin']['users']['enables']);
        }
        if (!empty($authList['admin']['users']['save'])) {
            $authList['admin']['users']['userSave'] = $authList['admin']['users']['save'];
            unset($authList['admin']['users']['save']);
        }
        if (!empty($authList['admin']['users']['update'])) {
            $authList['admin']['users']['userUpdate']  = $authList['admin']['users']['update'];
            unset($authList['admin']['users']['update']);
        }
        if (!empty($authList['admin']['users']['structures_save'])) {
            $authList['admin']['users']['deptSave'] = $authList['admin']['users']['structures_save'];
            unset($authList['admin']['users']['structures_save']);
        }
        if (!empty($authList['admin']['users']['structures_update'])) {
            $authList['admin']['users']['deptUpdate'] = $authList['admin']['users']['structures_update'];
            unset($authList['admin']['users']['structures_update']);
        }
        if (!empty($authList['admin']['users']['structures_delete'])) {
            $authList['admin']['users']['deptDelete'] = $authList['admin']['users']['structures_delete'];
            unset($authList['admin']['users']['structures_delete']);
        }
        # admin:group 角色权限管理
        if (!empty($authList['admin']['groups'])) {
            $authList['admin']['permission'] = $authList['admin']['groups'];
            unset($authList['admin']['groups']);
        }
        # admin:examine_flow
        if (!empty($authList['admin']['examine_flow'])) {
            $authList['admin']['examineFlow'] = $authList['admin']['examine_flow'];
            unset($authList['admin']['examine_flow']);
        }
        # admin:printing
        if (!empty($authList['admin']['printing'])) {
            $authList['admin']['print'] = $authList['admin']['printing'];
            unset($authList['admin']['printing']);
        }
        # admin:work
        if (!empty($authList['admin']['work']['work'])) {
            $authList['admin']['work']['update'] = $authList['admin']['work']['work'];
            unset($authList['admin']['work']['work']);
        }
        # admin:log
        unset($authList['admin']['loginrecord']);
        unset($authList['admin']['log']);
        # admin:initialize
        if (!empty($authList['admin']['initialize'])) {
            $authList['admin']['init']['initData'] = $authList['admin']['initialize']['update'];
            $authList['admin']['init']['index']    = $authList['admin']['initialize']['index'] ?? '';
            unset($authList['admin']['initialize']);
        }
        # admin
        if (!empty($authList['admin'])) {
            $authList['manage'] = $authList['admin'];
            $adminAuth = [
                'configSet.read', 'crm.achievement', 'crm.field', 'crm.pool', 'crm.setting',
                'examineFlow.index', 'init.initData', 'oa.examine', 'system.read', 'users.read',
                'work.update','permission.update'
            ];

            foreach ($authList['manage'] AS $key1 => $value1) {
                foreach ($value1 AS $key2 => $value2) {
                    if (in_array($key1.'.'.$key2, $adminAuth)) {
                        $authList['manage']['other_rule'] = [
                            'setwelcome'     => true,
                            'setworklogrule' => true,
                            'welcome'        => true,
                            'worklogrule'    => true
                        ];
                    }
                }
            }
        }
        if (empty($authList['manage']['other_rule'])) unset($authList['manage']);
        unset($authList['admin']);

        # 通讯录

      //  $authList['email']     = (Object)[];
      //  $authList['hrm']       = (Object)[];
      //  $authList['jxc']       = (Object)[];
      //  $authList['knowledge'] = (Object)[];

        return $authList;
    }

    /**
     * 获取权限结构数组
     * @param
     */
    public function getRulesList($uid)
    {
        $ruleMap = [];
        $adminTypes = adminGroupTypes($uid);
        if (in_array(1,$adminTypes)) {			
            $map['status'] = 1;
        } else {			 $groups = $this->get($uid)->groups;
            $ruleIds = [];
            foreach($groups as $k => $v) {
                if (stringToArray($v['rules'])) {
                    $ruleIds = array_merge($ruleIds, stringToArray($v['rules']));
                }
            }
            $ruleIds = array_unique($ruleIds);
            $ruleMap['id'] = array('in', $ruleIds);
            $ruleMap['status'] = 1;
        }		
        $newRuleIds = [];
        // 重新设置ruleIds，除去部分已删除或禁用的权限。
        $rules = Db::name('admin_rule')->where($ruleMap)->select()->toArray();
        foreach ($rules as $k => $v) {
            $newRuleIds[] = $v['id'];
            $rules[$k]['name'] = strtolower($v['name']);
        }
        //处理规则成树状
        $tree = new \com\Tree();
        $rulesList = $tree->list_to_tree($rules, 'id', 'pid', 'child', 0, true, array('pid'));
        $rulesList = rulesDeal($rulesList);
        return $rulesList ? : [];
    }

    /**
     * 获取用户所属角色（用户组）
     * @param
     */
    public function getGroupTypeByAction($uid, $m, $c, $a)
    {
        //根据$m,$c,$a 获取对应的$a 的rule_id
        $rulesList = $this->getRulesList($uid);
        if (!in_array($m.'-'.$c.'-'.$a, $rulesList)) {
            return false;
        }
        $mRuleId = Db::name('admin_rule')->where(['name'=>$m,'level'=>1])->value('id');
        $cRuleId = Db::name('admin_rule')->where(['name'=>$c,'level'=>2,'pid'=>$mRuleId])->value('id');
        $aRuleId = Db::name('admin_rule')->where(['name'=>$a,'level'=>3,'pid'=>$cRuleId])->value('id');
        //获取用户组
        $groups = $this->find($uid)->groups;
        if (!$groups) {
            return false;
        }
        $groupTypes = [];
        foreach ($groups as $g) {
            if (in_array($aRuleId, explode(',', trim($g['rules'], ',')))) {
                $groupTypes[] = $g['type'];
            }
        }
        return $groupTypes ? : [];
    }

    /**
     * 获取有此权限的角色
     * @param
     */
    public function getAllUserByAction($m, $c, $a)
    {
        $mRuleId = Db::name('admin_rule')->where(['name'=>$m,'level'=>1])->value('id');
        $cRuleId = Db::name('admin_rule')->where(['name'=>$c,'level'=>2,'pid'=>$mRuleId])->value('id');
        $aRuleId = Db::name('admin_rule')->where(['name'=>$a,'level'=>3,'pid'=>$cRuleId])->value('id');

        $groups = Db::name('admin_group')->where(['rules' => ['in',$aRuleId]])->column('id');
        $userIds = Db::name('admin_access')->where(['group_id' => ['in',$groups]])->column('user_id');
        if (!$userIds) {
            //查询管理员
            $userIds = Db::name('admin_user')->where(['id' => 1])->column('id');
        }
        return $userIds;
    }

    /**
     * 根据部门获取部门的userId
     * @param $strId  部门ID
     * @param $type  2时包含所有下属部门
     */
    public function getSubUserByStr($structure_id, $type = 1)
    {
        $allStrIds = (array) $structure_id;
        if ($type == 2) {
            $structureModel = new \app\admin\model\Structure();
            foreach ($allStrIds as $v) {
                $allSubStrIds = [];
                $allSubStrIds = $structureModel->getAllChild($v);
                if ($allSubStrIds) {
                    $allStrIds = array_merge($allStrIds, $allSubStrIds); //全部关联部门（包含下属部门）
                }
            }
        }
        // $userIds = Db::name('admin_user')->where(['structure_id' => ['in',$allStrIds]])->column('id');
        $userIds = Db::name('admin_user')->where('structure_id', 'in', $allStrIds)->column('id');
        return $userIds ? : [];
    }

    /**
     * [getUserById 根据主键获取详情]
     * @param
     * @return
     */
    public function getUserById($id = '',$field = '')
    {
        if(!$field){
            $field = [
                'user.id',
                'username',
                'img',
                'thumb_img',
                'realname',
                'parent_id',
                'structure.name' => 'structure_name',
                'structure.id' => 'structure_id'
            ];
        }
        $data = Db::name('AdminUser')
            ->alias('user')
            ->join('admin_structure structure', 'structure.id = user.structure_id', 'LEFT')
            ->where(['user.id' => $id])
            ->field($field)
            //->cache('user_info' . $id, null, 'user_info')
            ->find();
        if(isset($data['parent_id'])){
            $parentData = Db::name('admin_user')->where('id','=',$data['parent_id'])->field('realname,mobile')->find();
            $data['parent_name'] = $parentData['realname'] ?? '';
            $data['parent_mobile'] = $parentData['mobile'] ?? '';
        }
        if(isset($data['thumb_img'])){
            $data['thumb_img'] = $data['thumb_img'] ?  config('app.img_url').$data['thumb_img'] : '';
        }
        return $data ? : [];
    }

    /**
     * [getUserNameById 根据主键获取详情]
     * @param
     * @return
     */
    public function getUserNameById($id = '')
    {
        $data = $this->where(['id' => $id])->value('realname');
        return $data ? : '查看详情';
    }

    /**
     * [getUserNameByArr 根据主键获取详情]
     * @param
     * @return
     */
    public function getUserNameByArr($ids = [])
    {
        if (!is_array($ids)) {
            $idArr[] = $ids;
        } else {
            $idArr = $ids;
        }
        $data = $this->where(['id' => array('in', $idArr)])->column('realname');
        return $data ? : [];
    }

    /**
     * [getAdminId 获取管理员ID]
     * @param
     * @return
     */
    public function getAdminId()
    {
        $adminGroupUser =  Db::name('admin_access')->where(['group_id' => 1])->column('user_id');
        $userIDs = $adminGroupUser ? array_merge($adminGroupUser, [1]) : [1];
        return $userIDs ? : [1];
    }

    /**
     * [getUserByIdArr 根据ID数组获取列表]
     * @param
     * @return
     */
    public function getUserByIdArr($ids = [])
    {
        $list = $this
            ->alias('user')
            ->join('__ADMIN_STRUCTURE__ structure', 'structure.id = user.structure_id', 'LEFT')
            ->where(['user.id' => ['in', $ids]])->field('user.id,username,img,thumb_img,realname,parent_id,structure.name as structure_name,structure.id as structure_id')->select();
        return $list ? : [];
    }

    /**
     * [getUserByPer 获取权限范围的user_id]
     * @param
     * @return
     */
    public function getUserByPer($m = '', $c = '', $a = ''){
        $request = request();;
        $header = $request->header();
        $authKey = $header['auth-key'];

        $m = $m ? strtolower($m) : strtolower(app()->http->getName());
        $c = $c ? strtolower($c) : strtolower($request->controller());
        $a = $a ? strtolower($a) : strtolower($request->action());

        $cache = cache('auth:'.$authKey);
        if (!$cache) {
            return false;
        }
        $userInfo = $cache['userInfo'];
        //用户所属用户组类别（数组）
        $groupTypes = $this->getGroupTypeByAction($userInfo['id'], $m, $c, $a);
        //数组去重
        $groupTypes = $groupTypes ? array_unique($groupTypes) : [];
        //用户组类别（1本人，2本人及下属，3本部门，4本部门及下属部门，5全部）
        $adminIds = $this->getAdminId();
        $userIds = [];
        if (in_array($userInfo['id'],$adminIds)) {
            $userIds = getSubUserId(true, 1);
        } else {
            if (!$groupTypes) {
                return [];
            }
            if (in_array(5, $groupTypes)) {
                $userIds = getSubUserId(true, 1);

            } else {
                foreach ($groupTypes as $v) {
                    if ($v == 1) {
                        $userIds = [$userInfo['id']];
                    } elseif ($v == 2) {
                        $userIds = getSubUserId();
                    } elseif ($v == 3) {
                        $userIds = $this->getSubUserByStr($userInfo['structure_id']);
                    } elseif ($v == 4) {
                        $userIds = $this->getSubUserByStr($userInfo['structure_id'], 2);
                    }
                }
            }
        }
        return $userIds ? : [];
    }

    /*
    *根据部门ID获取员工列表
    *
    */
    public function getUserListByStructureId($structure_id='')
    {
        $map =array();
        if($structure_id){
            $map['structure_id'] = $structure_id;
        }
        $list = Db::name('AdminUser')->field('id as user_id,realname,post,structure_id')->where($map)->select();
        return $list ? : [];
    }

    /*
    *根据字符串返回数组
    *
    */
    public function getListByStr($str)
    {
        $idArr = stringToArray($str);
        $list = Db::name('admin_user')->field('id,username,realname,thumb_img')->where(['id' => ['in',$idArr]])->select();
        return $list;
    }

    /*
    *读写权限
    *
    */
    public function rwPre($user_id, $ro_user_id, $rw_user_id, $action = 'read')
    {
        if ($action == 'update') {
            if (!in_array($user_id, stringToArray($rw_user_id))) {
                return false;
            }
        } else {
            if (!in_array($user_id, stringToArray($ro_user_id))) {
                return false;
            }
        }
        return true;
    }

    /**
     * [getUserThree 员工第三方扩展信息]
     * @param  key 分类
     * @author Mr.Li
     * @return    [array]
     */
    public function getUserThree($key, $user_id)
    {
        $resValue = Db::name('admin_user_threeparty')->where(['key' => $key,'user_id' => $user_id])->value('value');
        return $resValue ? : '';
    }

    /**
     * 获取当前登录用户信息
     *
     * @param string $key	默认返回所有信息
     * @return mixed
     * @author Ymob
     * @datetime 2019-10-22 14:38:07
     */
    public static function userInfo($key = '')
    {
        $request = Request::instance();
        $header = $request->header();

        $authKey = $header['authkey'];
        $sessionId = $header['sessionid'];
        $paramArr = $request->param();
        $cache = cache('auth:' . $authKey);
        if ($cache) {
            if ($key) {
                return $cache['userInfo'][$key];
            } else {
                return $cache['userInfo'];
            }
        } else {
            return false;
        }
    }

    /**
     * 判断用户是否拥有 某(些) 角色
     *
     * @param array $group_list
     * @param integer $user_id
     * @return bool
     * @author Ymob
     * @datetime 2019-10-25 15:50:48
     */
    public static function checkUserGroup($group_list = [], $user_id = 0)
    {
        $user_id = $user_id ?: self::userInfo('id');
        if (empty($group_list))
            return !!Access::where(['user_id' => $user_id, 'group_id' => ['IN', $group]])->value('user_id');
    }

    /**
     * 顶部菜单栏显示
     * @param $param
     * @return array
     */
    public function sortList($param){
        $list=Db::name('admin_sort')->where('user_id',$param['user_id'])->field('value')->find();
        $list=unserialize($list['value']);
        return $list?:[];
    }

    /**
     * 修改顶部菜单显示
     * @param $param
     */
    public function updateSort($param){
        $list=Db::name('admin_sort')->where('user_id',$param['user_id'])->field('value')->select();
        if($list){
            $data= Db::name('admin_sort')->where('user_id',$param['user_id'])->update(['value'=>serialize($param['value'])]);
        }else{
            $data= Db::name('admin_sort')->insert(['user_id'=>$param['user_id'],'value'=>serialize($param['value'])]);
        }
        return $data;
    }

    /**
     * 复制员工角色
     *
     * @param $param
     * @return bool
     */
    public function copyRole($param)
    {
        $userIds      = !empty($param['user_id'])      ? $param['user_id']      : [];
        $structureIds = !empty($param['structure_id']) ? $param['structure_id'] : [];
        $groupIds     = !empty($param['group_id'])     ? $param['group_id']     : [];

        # 员工与角色关联数据
        $userGroup = [];

        # 查询部门下的员工ID
        if (!empty($structureIds)) {
            $userIds = Db::name('admin_user')->whereIn('structure_id', $param['structure_id'])->column('id');
            $userIds = array_unique((array)$userIds);
        }

        Db::startTrans();
        try{
            # 删除员工角色关联数据
            Db::name('admin_access')->whereIn('user_id', $userIds)->delete();

            # 重新设置员工角色
            foreach ($userIds AS $key => $value) {
                # 默认跳过超级管理员
                if ($value == 1) continue;

                foreach ($groupIds AS $k => $v) {
                    $userGroup[] = [
                        'user_id'  => $value,
                        'group_id' => $v
                    ];
                }
            }

            if (!empty($userGroup)) Db::name('admin_access')->insertAll($userGroup);

            Db::commit();

            return true;
        } catch (\Exception $e) {
            Db::rollback();

            return false;
        }
    }

    /**
     * 根据条件获取信息
     * @param  array $where 查询条件
     * @param  array $field 查询字段
     * @return array
     * @author Mr.Liu Wuchen
     * @create 2021-06-25 10:51
     */
    public function getUserList(array $where = [], array $field = []): array
    {
        try {
            $list = $this->where($where)->field($field)->select()->toArray();
        } catch (\Exception $e) {
        }

        return isset($list) && $list ? $list : [];
    }

    /**
     * 获取数据权限范围的uid
     * 返回 all 为全部 0 为无权限 其他为uid
     * @param  int    $userId 用户ID
     * @param  string $authType 类型
     * @return array|int[]|string[]
     * @author Mr.Liu Wuchen
     * @create 2021-07-01 8:14
     */
    public function getDataAuthUid(int $userId = 0, string $authType = ''): array
    {
        $return = [-1];
        try {
            // 获取数据权限类型
            $dataAuthTypeArr = $this->getDataAuthType($userId, $authType);
            if (in_array(-1, $dataAuthTypeArr) || in_array('all', $dataAuthTypeArr)) {
                return $dataAuthTypeArr;
            }
            $dataAuthType = $dataAuthTypeArr[0];

            // 员工信息
            $userInfo = $this->where('id', '=', $userId)->find();
            if (!$userInfo) {
                return $return;
            }

            // 获取数据权限最大值
            // 1本人，2本人及下属，3本部门，4本部门及下属部门，5全部
            switch ($dataAuthType) {
                case 1:
                    $userIds = [$userId];
                    break;
                case 2:
                    $nextUser = getSubUser($userId);
                    $userIds  = $nextUser && is_array($nextUser) ? $nextUser : [];
                    array_unshift($userIds, $userId);
                    break;
                case 3:
                    $userIds = $this->getSubUserByStr($userInfo['structure_id']);
                    break;
                case 4:
                    $userIds = $this->getSubUserByStr($userInfo['structure_id'], 2);
                    break;
                case 5:
                    $userIds = ['all'];
                    break;
                default:
                    $userIds = $return;
                    break;
            }
            $return = $userIds;
        } catch (\Exception $e) {
        }

        return $return;
	}

	/**
     * 获取数据权限类型
     * 返回 all 为全部 0 为无权限 其他为uid
     * @param  int    $userId 用户ID
     * @param  string $authType 类型
     * @return array|int[]|string[]
     * @author Mr.Liu Wuchen
     * @create 2021-08-12 11:40
     */
    public function getDataAuthType(int $userId = 0, string $authType = ''): array
    {
        $return = [-1];
        try {
            if (!$userId || !$authType) {
                return $return;
            }

            // 判断是否是超级管理员 超级管理员返回全部
            if(in_array($userId, getSuperAdminId())) {
                return ['all'];
            }

            // 获取用户角色组ID
            $where = [
                ['user_id', '=', $userId],
                ['group_id', '<>', 1]
            ];
            $groupIdArr = Db::name('admin_access')->where($where)->column('group_id');
            if (!$groupIdArr) {
                return $return;
            }

            $authField    = [];
            // 获取角色数据权限
            $dataAuthList = Db::name('admin_data_auth')->where('group_id', 'in', array_unique($groupIdArr))->select()->toArray();
            foreach ($dataAuthList as $key => $val) {
                foreach ($val as $k => $v) {
                    $authField[$k][] = $v;
                }
            }

            if (!isset($authField[$authType]) || !$authField[$authType]) {
                return $return;
            }
            $dataAuthType = max($authField[$authType]);
            if (!in_array($dataAuthType, [1, 2, 3, 4, 5])) {
                return $return;
            }

            // 获取数据权限最大值
            // 1本人，2本人及下属，3本部门，4本部门及下属部门，5全部
            $return = [$dataAuthType];
        } catch (\Exception $e) {
        }

        return $return;
	}



    /**
     * 批量创建用户
     * @param array $param
     * @return bool
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     * @author Mr.Li
     * @create 2021-06-05 11:50
     */
    public function createBatchData($param)
    {

        // 验证
        $validate = new \app\admin\validate\AdminUser();
        $insertUsers = [];
        $structData = Db::name('AdminStructure')->column('id','name');
        foreach($param as $v){
            $insertUsers[] = [
                'username'                  => trim($v[0]) ?? '',
                'realname'                  => $v[1] ?? '',
                'email'                     => $v[2] ?? '',
                'mobile'                    => $v[3] ?? '',
                'sex'                       => $v[4] ?? '',
                'structure_id'              => $structData[$v[5]] ?? '',
                'kingdee_salesperson_code'  => $v[7] ?? '',
                'post'                      => $v[6] ?? '',
                'status'                    => $v[8] ?? 0,
                'parent_id'                 => 2,
                'group_id'                  => [2],
                'type'                      => 1 //系统用户
            ];
        }
        foreach($insertUsers as $user){
            if (!$validate->check($user)) {
                $this->error = $validate->getError();
                return false;
            }
        }
        $password = (new Password())->getDefaultPwd();
        unset($param);
        $this->startTrans();
        try {
            foreach($insertUsers as $param){

                    $salt = substr(md5(time()),0,4);
                    $param['salt'] = $salt;
                    $param['password'] = user_md5($password, $salt, $param['username']);
                    $param['type'] = $param['type'];
                    $param['mobile'] = $param['username'];
                    $groupId = $param['group_id'];
                    unset($param['group_id']);
                    unset($param['groupids']);
                    $param['create_time'] = time();
                    $user_id = $this->insertGetId($param);
                    //员工档案
                    $data['user_id'] = $user_id;
                    $data['mobile'] = $param['username'];
                    $data['email'] = $param['email'] ?? '';
                    $data['sex'] = $param['sex'] ? : '';
                    $data['create_time'] = time();
                    Db::name('AdminHrmUserDet')->insert($data);

                    $userGroups = [];
                    foreach ($groupId as $k => $v) {
                        $userGroup['user_id'] = $user_id;
                        $userGroup['group_id'] = $v;
                        $userGroups[] = $userGroup;
                    }
                    if ($userGroups) {
                        Db::name('admin_access')->insertAll($userGroups);
                    }

                    $this->commit();
                    $param['user_id'] = $data['user_id'];
                    // $resSync = $syncModel->syncData($param);

            }
        } catch(\Exception $e) {
            $this->rollback();
            $this->error = '添加失败';
            return false;
        }
        return true;
        // $syncModel = new \app\admin\model\Sync();

    }

    /**
     * 更换员工头像
     * @param $userId
     * @param $imgPath
     * @throws DbException
     * @author Mr.Li
     * @create 2021-07-05 16:58
     */
    public function updateImg($userId,$imgPath){
        return  Db::name('admin_user')->where('id','=',$userId)->update(['thumb_img'=>$imgPath]);
    }

    /**
     * 获取所有未禁用用户
     * @param $params
     * @return \think\Collection
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     * @author Mr.Li
     * @create 2021-07-13 16:37
     */
    public function all($params)
    {

        if (isset($params['search']) && $params['search']) {
            // $map['user.username|user.realname'] = ['like', '%'.$map['search'].'%'];
            $map[] = ['username|realname', 'like', '%'.$params['search'].'%'];
        }
        $map[] = ['status','<>',0];
        return Db::name('admin_user')->where($map)->field('id,realname')->select();
    }

    /**
     * 获取平台锁定Key
     * @param $platform
     * @param $userId
     * @author Mr.Li
     * @create 2021-08-03 10:56
     */
    protected function getLockKey($platform,$userId)
    {
        $appType =  config('password')['app_type'] ?? [];
        $platform = isset($appType[$platform]) ? $appType[$platform] : 'pc';
        $platform = '_'.$platform;
        return $this->lockKey.$platform.$userId;
    }


    /**
     *  清除锁定记录
     * @param $platform
     * @param $userId
     * @return bool
     * @author Mr.Li
     * @create 2021-07-29 14:56
     */
    protected function clearLock($platform,$userId)
    {

        $cacheKey = $this->lockKey.$userId;
        if(Cache::has($cacheKey)){
            Cache::delete($cacheKey);
        }
        return true;
    }
    /**
     * 检测登录锁定
     * @param $platform
     * @param $userId
     * @author Mr.Li
     * @create 2021-07-29 10:53
     */
    protected function isLock($platform,$userId)
    {
        /*
         * 区分平台解锁
         *  $cacheKey = $this->getLockKey($platform,$userId);
         */
        $cacheKey = $this->lockKey.$userId;
        $cacheLockInfo = Cache::get($cacheKey);
        if($cacheLockInfo){
            if(!isset($cacheLockInfo['lock_time'])){
                return false;
            }
            $diffTime = $cacheLockInfo['lock_time'] - time();
            if($diffTime > 0){
                $this->lockMsg = '需要'.getTimeBySec($diffTime).'解锁';
                if(mb_strpos($this->lockMsg,'年') !== false){
                    $this->lockMsg = self::LOCK_ACCOUNT_PERMANENT_MSG;
                }
                return true;
            }else{//锁定时间过期，重新计数
                $cacheLockInfo['lock_attempt_count'] = 0;
                unset($cacheLockInfo['lock_time']);
                Cache::set($cacheKey,$cacheLockInfo);
            }
        }
        return false;
    }

    /**
     * 处理用户登录锁定
     * @param $platform
     * @param $userId
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     * @author Mr.Li
     * @create 2021-07-29 10:56
     */
    protected function lockOperate($platform,$userId)
    {

        $pwdRule =  Db::name('admin_pwd_rule')->order('id','asc')->find();
        if($pwdRule){//如果设置了密码策略 根据密码策略处理
            if($pwdRule['is_lock']){//开启登录锁定
                if($pwdRule['lock_option_type']){
                    $ruleType = config('password')['pwd_rule'] ?? [];
                    /*
                     * 区分平台解锁
                    */
                    $cacheKey = $this->lockKey.$userId;
                    $cacheLockInfo = Cache::get($cacheKey);
                    if ($cacheLockInfo) {
                        $info = $cacheLockInfo;
                        if($cacheLockInfo['lock_attempt_count'] >= $pwdRule['lock_attempt_count']){//登录失败次数超过设定次数
                            if(isset($cacheLockInfo['level'])){
                                $info['level'] =  $cacheLockInfo['level'] + 1;
                                if($pwdRule['lock_option_type'] == 1){//逐级递增
                                    if($info['level'] > 0 && $info['level'] < 8){
                                        $info['lock_time'] = time() + $ruleType[$pwdRule['lock_option_type']][$info['level']]['minute'] * 60;
                                        $this->lockMsg = '密码错误超过最大限制,账号锁定'.$ruleType[$pwdRule['lock_option_type']][$info['level']]['msg'];
                                    }else{
                                        $this->lockMsg = self::LOCK_ACCOUNT_PERMANENT_MSG;
                                        $info['lock_time'] = strtotime('+10 year');
                                    }
                                }else if($pwdRule['lock_option_type'] == 2){//固定
                                    if($info['level'] >= $pwdRule['lock_option_attempt_count']){//永久锁定
                                        $info['lock_time'] = strtotime('+10 year');
                                        $this->lockMsg = self::LOCK_ACCOUNT_PERMANENT_MSG;
                                    }else{
                                        $info['lock_time'] = time() + $pwdRule['lock_option_attempt_minute'] * 60;
                                        $this->lockMsg = '密码错误超过最大限制,账号锁定'.$pwdRule['lock_option_attempt_minute'].'分钟';
                                    }

                                }

                            } else{//首次失败设置过期时间和等级初始值
                                if($pwdRule['lock_option_type'] == 1) {//逐级递增
                                    $info['lock_time'] = time() + $ruleType[$pwdRule['lock_option_type']][1]['minute'] * 60;
                                    $this->lockMsg = '密码错误超过最大限制,账号锁定'.$ruleType[$pwdRule['lock_option_type']][1]['msg'];
                                }else if($pwdRule['lock_option_type'] == 2){//固定
                                    $info['lock_time'] = time() + $pwdRule['lock_option_attempt_minute'] * 60;
                                    $this->lockMsg = '密码错误超过最大限制,账号锁定'.$pwdRule['lock_option_attempt_minute'].'分钟';
                                }
                                $info['level'] = 1;
                            }
                        }else{
                            $info['lock_attempt_count'] = $cacheLockInfo['lock_attempt_count'] + 1;
                        }

                    }else{
                        $info['lock_attempt_count'] = 1;
                    }
                    Cache::set($cacheKey,$info);
                }
            }


        }
        if(!$this->lockMsg){
            $this->lockMsg = '账号密码不正确';
        }
        return $this->lockMsg;

    }


    /**
     * 解除账号锁定
     * @param $userId
     * @author Mr.Li
     * @create 2021-07-30 17:13
     */
    public function unlockAccountPassword($userId)
    {
        /*
         区分平台解锁开始
        $appType =  array_unique(array_values(config('password')['app_type'])) ?? [];
        foreach($appType as $app){
            $platform = '_'.$app;
            $cacheKey = $this->lockKey.$platform.$userId;
            if(Cache::has($cacheKey)){
                $isLock = true;
            }
        }
        */
        $cacheKey = $this->lockKey.$userId;
        if(Cache::has($cacheKey)){
            $isLock = true;
        }
        if(!isset($isLock)){
            $this->error = '账号没有锁定，无需解锁';
            return false;
        }
        Cache::delete($cacheKey);
        return true;
        /*
         *
        foreach($appType as $app){
            $platform = '_'.$app;
            $cacheKey = $this->lockKey.$platform.$userId;
            Cache::delete($cacheKey);
        }
        区分平台解锁结束
        */

    }

    /**
     * 员工状态更新
     * @param  array $request 请求参数
     * @return bool
     * @author Mr.Liu Wuchen
     * @create 2021-07-31 14:36
     */
    public function updateStatusData(array $request): bool
    {
        try {
            $status = isset($request['status']) ? intval($request['status']) : 0;
            $id     = $request['id'] ?? [];
            if (!$id || !in_array($status, [0, 1])) {
                $this->error = '参数错误';
                return false;
            }
            $idArr = !is_array($id) ? [$id] : $id;
            $where = [
                ['id', 'in', $idArr],
                ['id', '>', 1]
            ];
            $list  = $this->where($where)->select()->toArray();
            if (!$list) {
                $this->error = '员工信息不存在';
                return false;
            }
            $idArr   = array_unique(array_column($list, 'id'));
            $listArr = array_column($list, null, 'id');
            if ($status == 1) {
                // 启用
                $parentIdArr = array_unique(array_column($list, 'parent_id'));
                $where = [
                    ['id', 'in', $parentIdArr],
                    ['status', '=', 0]
                ];
                $field      = ['id'];
                $parentList = $this->where($where)->field($field)->select()->toArray();
                if ($parentList) {
                    if (!is_array($id)) {
                        // 单个设置
                        $msg = '当前员工的直属上级已被禁用，请先修改当前员工的直属上级';
                    } else {
                        // 批量设置
                        $parentName  = [];
                        $parentIdArr = array_unique(array_column($parentList, 'id'));
                        foreach ($list as $key => $val) {
                            if (in_array($val['parent_id'], $parentIdArr)) {
                                array_push($parentName, $val['realname']);
                            }
                        }
                        $msg = '选中的员工【' . implode('、', $parentName) . '】的直属上级已被禁用，不能被启用，请先修改员工的直属上级';
                    }
                    $this->error = $msg;
                    return false;
                }
            } else {
                $field      = ['id', 'parent_id'];
                $parentList = $this->where('parent_id', 'in', $idArr)->field($field)->select()->toArray();
                if ($parentList) {
                    if (!is_array($id)) {
                        // 单个设置提醒
                        $msg = '当前员工已被设置为直属上级，不能被禁用';
                    } else {
                        // 批量设置提醒
                        $parentName  = [];
                        $parentIdArr = array_unique(array_column($parentList, 'parent_id'));
                        foreach ($parentIdArr as $key => $val) {
                            array_push($parentName, $listArr[$val]['realname'] ?? '');
                        }
                        $msg = '选中的员工【' . implode('、', $parentName) . '】被设置为直属上级，不能被禁用，请重新选择';
                    }
                    $this->error = $msg;
                    return false;
                }
            }

            $bool = $this->where('id', 'in', $idArr)->update(['status' => $status]);
            if ($bool >= 0) {
                // 添加操作记录
                $statusArr = ['0' => '禁用', '1' => '启用', '2' => '未激活'];
                foreach ($list as $key => $val) {
                    $statusName = $statusArr[$val['status']] ?? '未知';
                    $logContentStr = "将 '员工状态' 由 " . $statusName . " 修改为 " . $statusArr[$status];
                    $logCode = json_encode($val, JSON_UNESCAPED_UNICODE);
                    $this->addActionRecord($request['user_id'], 'admin_user_status', $val['id'], $logContentStr, 'admin', 'users', $logCode);
                }

                $this->error = '更新成功';
                return true;
            }
        } catch (\Exception $e) {
        }

        $this->error = '更新失败';
        return false;
    }

    /**
     * 批量选择上级
     * @param  array $request 请求参数
     * @return array
     * @author Mr.Liu Wuchen
     * @create 2021-07-31 16:40
     */
    public function getSelectParentData(array $request): array
    {
        try {
            $structureId = isset($request['structure_id']) && intval($request['structure_id']) ? intval($request['structure_id']) : 0;
            if (!$structureId) {
                $this->error = '请先选择部门';
                return [];
            }
            // 获取所有直属上级
            $pidArr = (new \app\admin\model\Structure())->getAllParent($structureId);
            array_push($pidArr, $structureId);
            $where = [
                ['structure_id', 'in', array_unique($pidArr)],
                ['status', '<>', 0]
            ];
            $field = ['id', 'realname'];
            $list  = Db::name('admin_user')->where($where)->field($field)->select()->toArray();

            $this->error  = '获取成功';
            $data['data'] = $list ?: [];
            return $data;
        } catch (\Exception $e) {
        }

        $this->error = '暂无数据';
        return [];
	}

    /**
     * 是否跳转需要修改密码
     * @return bool
     * @author Mr.Li
     * @create 2021-07-31 14:38
     */
    protected function isLoginJump()
    {
        $isModify =  Db::name('admin_pwd_rule')->order('id','asc')->value('is_force_modify');
        if($isModify){
            return true;
        }
        return false;
    }


    /**
     * 批量更新直属上级
     * @param  array $request 请求参数
     * @return bool
     * @author Mr.Liu Wuchen
     * @create 2021-07-31 17:06
     */
    public function updateParentData(array $request): bool
    {
        try {
            $idArr       = $request['id'] ?? [];
            $structureId = isset($request['structure_id']) && intval($request['structure_id']) ? intval($request['structure_id']) : 0;
            $parentId    = isset($request['parent_id']) && intval($request['parent_id']) ? intval($request['parent_id']) : 0;
            if (!$idArr || !is_array($idArr)) {
                $this->error = '请选择员工';
                return false;
            }
            if (!$structureId) {
                $this->error = '请先选择部门';
                return false;
            }
            if (!$parentId) {
                $this->error = '请选择直属上级';
                return false;
            }

            // 排除超级管理员
            $where = [
                ['id', 'in', $idArr],
                ['structure_id', '=', $structureId],
                ['id', '>', 1]
            ];
            $list = $this->where($where)->select()->toArray();
            if (!$list) {
                $this->error = '该部门下员工信息不存在';
                return false;
            }

            // 判断选择的直属上级是否符合
            $idArr      = array_column($list, 'id');
            $list       = array_column($list, null, 'id');
            $parentList = $this->getSelectParentData(['structure_id' => $structureId]);
            $listData = isset($parentList['data']) && $parentList['data'] ? array_column($parentList['data'], 'id') : [];
            if (!in_array($parentId, $listData)) {
                $this->error = '选择直属上级不合规则，请刷新后重试';
                return false;
            }
        } catch (\Exception $e) {
            $this->error = '更新失败';
            return false;
        }

        Db::startTrans();
        try {
            $parentIdArr = array_unique(array_column($list, 'parent_id'));
            array_push($parentIdArr, $parentId, 1); // 本部门中员工被设置为直属上级
            $parentNameList = $this->where('id', 'in', $parentIdArr)->select()->toArray();
            $parentNameList && $parentNameList = array_column($parentNameList, null, 'id');
            $parentInfo     = $parentNameList[$parentId] ?? [];
            if (!$parentInfo) {
                throw new \Exception('获取直属上级信息失败');
            }

            // 获取本部门下的员工
            $structureUserIdArr = $this->where('structure_id', '=', $structureId)->column('id');
            if (in_array($parentId, $structureUserIdArr)) {
                // 直属上级存在本部门中 则设置为 超级管理员
                if ($parentInfo['parent_id'] != 1) {
                    $bool = $this->where('id', '=', $parentId)->update(['parent_id' => 1]);
                    if ($bool >= 0) {
                    } else {
                        throw new \Exception('更新本部门中员工直属上级失败');
                    }
                }
                // 去掉已经更新的ID
                if (array_key_exists($parentId, $list)) {
                    unset($list[$parentId]);
                }

                // 如果上级一样则不写记录
                if ($parentInfo['parent_id'] != 1) {
                    $parentNameOld = $this->where('id', '=', $parentInfo['parent_id'])->value('realname', '');
                    $parentNameNew = $parentNameList[1]['realname'] ?? '';
                    $logContentStr = "将 '直属上级' 由 " . $parentNameOld . " 修改为 " . $parentNameNew;
                    $logCode       = json_encode($parentInfo, JSON_UNESCAPED_UNICODE);
                    $this->addActionRecord($request['user_id'], 'admin_user_parent', $parentId, $logContentStr, 'admin', 'users', $logCode);
                }
            }

            // 重新获取需要更新的ID
            if ($list) {
                $idArr = array_column($list, 'id');
                $bool  = $this->where('id', 'in', $idArr)->update(['parent_id' => $parentId]);
                if ($bool >= 0) {
                } else {
                    throw new \Exception('更新员工直属上级失败');
                }

                // 添加操作记录
                $parentInfoNew = $parentNameList[$parentId]['realname'] ?? [];
                foreach ($list as $key => $val) {
                    if ($val['parent_id'] != $parentId) {
                        $parentNameOld = $parentNameList[$val['parent_id']]['realname'] ?? '';
                        $logContentStr = "将 '直属上级' 由 " . $parentNameOld . " 修改为 " . $parentInfoNew;
                        $logCode       = json_encode($val, JSON_UNESCAPED_UNICODE);
                        $this->addActionRecord($request['user_id'], 'admin_user_parent', $val['id'], $logContentStr, 'admin', 'users', $logCode);
                    }
                }
            }

            Db::commit();

            $this->error = '更新成功';
            return true;
        } catch (\Exception $e) {
            Db::rollback();
            $this->error = $e->getMessage();
        }

        return false;
	}


	/**
     * 用户中心
     * @param $id
     * @author Mr.Li
     * @create 2021-08-02 14:46
     */
    public function center($id)
    {
        $field = [
            'user.id',
            'user.realname',
            'user.thumb_img',
            'user.parent_id',
            'user.post',
            'user.sex',
            'user.email',
            'user.mobile',
            'structure.name' => 'structure_name',
            'structure.id' => 'structure_id'
        ];
        $data['user_info'] = $this->getUserById($id,$field);
        unset($data['user_info']['parent_id'],$data['user_info']['structure_id'],$data['user_info']['img']);
        $permission = get_user_permission_menu($id,'home_list_tag');
        $data['data_info'] = [];
        if($permission) {
            $ret = [
                'LeadsList'    => ['class'    => LeadsLogic::class,'name' => '线索','type' => 'leads'],
                'Customer'     => ['class'    => CustomerLogic::class,'name' => '客户','type' => 'customer'],
                'Business'     => ['class'    =>  BusinessLogic::class,'name' => '商机','type' => 'business'],
            ];
            $client = new ClientLogic();
            in_array('*',$permission,true) ? $isSuper = true : $isSuper = false;
            foreach($ret as $menu => $menuData){
                if($isSuper || (isset($permission[$menu]) && $permission[$menu])) {
                        $data['data_info'][] = [
                            'name'              => $menuData['name'],
                            'module_type'       => $menuData['type'],
                            'value'             => $client->getSummaryData($menuData['class'] ,$id,[])
                        ];
                }
            }

        }
        return $data;
    }


    /**
     * 检测用户是否登录锁定
     * @param $platform
     * @param $userId
     * @return bool
     * @author Mr.Li
     * @create 2021-08-03 10:44
     */
    protected function isUserLoginLock($platform,$userId)
    {
        $cacheKey = $this->lockKey.$userId;
        $cacheLockInfo = Cache::get($cacheKey);
        if($cacheLockInfo){
            if(!isset($cacheLockInfo['lock_time'])){
                return false;
            }
            $diffTime = $cacheLockInfo['lock_time'] - time();
            if($diffTime > 0){
                return true;
            }
        }
        return false;
    }

    /**
     * 获取触达人、转化人
     * @param  array $request 请求参数
     * @return array
     * @author Mr.Liu Wuchen
     * @create 2021-08-21 11:46
     */
    public function getTouchTransUser(array $request): array
    {
        try{
            $type = $request['type'] ?? '';
            $id   = $request['id'] ?? 0;
            $name = $request['name'] ?? '';
            if (!in_array($type, ['leads', 'customer']) || !$id) {
                return [];
            }
            $userId      = $request['user_id'];
            $dataAuthUid = (new \app\admin\model\User())->getDataAuthUid($userId, $type);
            if (!in_array(-1, $dataAuthUid)) {
                // 跟进线索获取线索区域
                $field     = ['province_id', 'city_id', 'county_id', 'touch_user_id'];
                $leadsInfo = (new \app\crm\model\Leads())
                    ->when($type == 'leads', function ($query) use ($id) {
                        $query->where('leads_id', '=', $id);
                    })
                    ->when($type == 'customer', function($query) use ($id) {
                        $query->where('customer_id', '=', $id);
                    })
                    ->field($field)->find()->toArray();
                $areaIdArr = [$leadsInfo['province_id'] ?? 0, $leadsInfo['city_id'] ?? 0, $leadsInfo['county_id'] ?? 0];
                $areaIdArr = array_unique($areaIdArr);
                if ($areaIdArr) {
                    // 获取区域下的部门
                    $regionStructureIdArr = Db::name('admin_structure_region')
                        ->where('last_area', 'in', $areaIdArr)->column('structure_id');
                    if ($regionStructureIdArr) {
                        $regionStructureIdArr = array_unique($regionStructureIdArr);
                        $pidLevelArr = Db::name('admin_structure')->where('id', 'in', $regionStructureIdArr)->column('pid_level');
                    }
                    $structureIdArr = [];
                    if (isset($pidLevelArr) && $pidLevelArr) {
                        foreach ($pidLevelArr as $key => $val) {
                            $preIdArr       = array_values(array_filter(explode('-', $val)));
                            $structureIdArr = array_merge($structureIdArr, $preIdArr);
                        }
                    }
                    $regionStructureIdArr && $structureIdArr = array_merge($structureIdArr, $regionStructureIdArr);
                }

                $field = ['id, realname'];
                $map   = [
                        ['status', '<>', 0]
                    ];
                $name && array_push($map, ['realname', 'like', '%' . $name . '%']);
                if(!in_array('all', $dataAuthUid)){
                    array_push($map, ['id', 'in', $dataAuthUid]);
                }
                $list = [];
                if (isset($structureIdArr) && $structureIdArr) {
                    array_push($map, ['structure_id', 'in', array_unique($structureIdArr)]);
                    $list = (new \app\admin\model\User)->getUserList($map, $field);
                }

                if ($type == 'leads') {
                    // 触达人
                    $touchTransUserId = $leadsInfo['touch_user_id'] ?? 0;
                } else {
                    // 转化人
                    $touchTransUserId = Db::name('crm_customer')->where('customer_id', '=', $id)->value('trans_user_id', 0);
                }

                // 获取当前线索触达人
                if ($touchTransUserId) {
                    // 已经存在的触达人或转化人 需要显示
                    $touchInfo = (new \app\admin\model\User)->where('id', '=', $touchTransUserId)->field(['id, realname'])->find();
                    if ($list) {
                        ($touchInfo && !in_array($touchTransUserId, array_column($list, 'id'))) && array_unshift($list, $touchInfo);
                    } else {
                        $touchInfo && array_unshift($list, $touchInfo);
                    }
                }
            }
        }catch (\Exception $e){
            $list = [];
        }

        return $list ?? [];
    }


    /**
     *  更新员工部门id
     * @author lilongfei
     * @date 2021-09-11 15:55
     */
    public function  updateUserStructId($params)
    {


        $structData = [];
        if(!empty($params)){
            foreach($params as $v){
                if($v[6] && $v[5]){

                    $pid = Db::name('AdminStructure')->where('name',$v[5])->value('id');
                    if($pid){
                        $id = Db::name('AdminStructure')->where([['pid','=',$pid],['name','=',$v[6]]])->value('id');
                        if($v[7] && $id){//如果有第三级直接用第三级名称
                            $id = Db::name('AdminStructure')->where([['pid','=',$id],['name','=',$v[7]]])->value('id');
                        }else{
                            if(!$id){//说明是第四级的部门
                                $ids = Db::name('AdminStructure')->where([['pid','=',$pid]])->column('id');
                                if($ids){
                                    $id = Db::name('AdminStructure')->where([['pid','in',$ids],['name','=',$v[6]]])->value('id');
                                }
                            }
                        }

                        if(!$id){
                            echo $v[0].' '.$v[1]."\n";
                        }
                        if($id){
                            $data = Db::name('admin_user')->where('username',$v[0])->update(['structure_id' => $id]);

                        }

                    }

                }
            }
        }
        return true;
    }

}
